package de.mischa.nichtraucher;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.FeatureInfo;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

/**
 * Simple notes database access helper class. Defines the basic CRUD operations
 * for the notepad example, and gives the ability to list all notes as well as
 * retrieve or modify a specific note.
 * 
 * This has been improved from the first version of this tutorial through the
 * addition of better error handling and also using returning a Cursor instead
 * of using a collection of inner classes (which is less scalable and not
 * recommended).
 */
public class DbAdapter {

	public static final String KEY_YEAR = "year";
	public static final String KEY_MONTH = "month";
	public static final String KEY_DAY = "day";
	public static final String KEY_HOUR = "hour";
	public static final String KEY_MINUTE = "minute";
	public static final String KEY_COUNT = "count";
	public static final String KEY_PARCELCOST = "parcel_cost";
	public static final String KEY_PARCELCOUNT = "parcel_count";
	public static final String KEY_ID = "_id";
	public static final String KEY_CURRENCY ="currency";

	private static final String TAG = "dbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE = "create table entry (_id integer primary key autoincrement, "
			+ "year integer not null, month integer not null, day integer not null, "
			+ "hour integer not null, minute integer not null, "
			+ "count integer not null, parcel_cost double not null, "
			+ "parcel_count integer not null, currency Text not null);";

	private static final String DATABASE_NAME = "Nichtraucher";
	private static final String DATABASE_TABLE = "entry";
	private static final int DATABASE_VERSION = 3;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		} 

		@Override
		public void onCreate(SQLiteDatabase db) {

			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
		
			db.execSQL("ALTER TABLE entry ADD currency Text not null DEFAULT 'EUR'");
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public DbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the notes database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();

		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new note using the title and body provided. If the note is
	 * successfully created return the new rowId for that note, otherwise return
	 * a -1 to indicate failure.
	 * 
	 * @param title
	 *            the title of the note
	 * @param body
	 *            the body of the note
	 * @return rowId or -1 if failed
	 */
	public long createEntry(int year, int month, int day, int hour, int minute,
			int count, double parcelCost, int parcelCount, String currency) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_COUNT, count);
		initialValues.put(KEY_YEAR, year);
		initialValues.put(KEY_MONTH, month);
		initialValues.put(KEY_DAY, day);
		initialValues.put(KEY_HOUR, hour);
		initialValues.put(KEY_MINUTE, minute);
		initialValues.put(KEY_PARCELCOST, parcelCost);
		initialValues.put(KEY_PARCELCOUNT, parcelCount);
		initialValues.put(KEY_CURRENCY, currency);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	

	/**
	 * Return a Cursor over the list of all notes in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor fetchEntry() {

		return mDb.query(DATABASE_TABLE, new String[] { KEY_ID, KEY_YEAR,
				KEY_MONTH, KEY_DAY, KEY_HOUR, KEY_MINUTE, KEY_PARCELCOST,
				KEY_COUNT, KEY_PARCELCOUNT, KEY_CURRENCY }, null, null, null, null, null);
	}

	

	/**
	 * Update the note using the details provided. The note to be updated is
	 * specified using the rowId, and it is altered to use the title and body
	 * values passed in
	 * 
	 * @param rowId
	 *            id of note to update
	 * @param title
	 *            value to set note title to
	 * @param body
	 *            value to set note body to
	 * @return true if the note was successfully updated, false otherwise
	 */
	public boolean updateEntry(int year, int month, int day, int hour,
			int minute, int count, double parcelCost, int parcelCount, String currency) {
		mDb.delete(DATABASE_TABLE, null, null);
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_COUNT, count);
		initialValues.put(KEY_YEAR, year);
		initialValues.put(KEY_MONTH, month);
		initialValues.put(KEY_DAY, day);
		initialValues.put(KEY_HOUR, hour);
		initialValues.put(KEY_MINUTE, minute);
		initialValues.put(KEY_PARCELCOST, parcelCost);
		initialValues.put(KEY_PARCELCOUNT, parcelCount);
		initialValues.put(KEY_CURRENCY, currency);

		return mDb.insert(DATABASE_TABLE, null, initialValues) > 0;
	}
}
